<%
# -*- mode: R -*-
  strategico.home <- as.character(Sys.getenv("STRATEGICO_HOME"))
  source(file.path(strategico.home, "strategico_util.R"))
    
  project.name <- ifelse(is.null(POST$project), GET$project, POST$project)
  project.values <- Project.GetValues(project.name=project.name)


  MySource("strategico_web.R")

  page.title <- " "
  page.sections	<- data.frame()

  if (!is.null(project.name) && !is.null(POST$import.csv) && !is.null(FILES) && !is.null(FILES$project_file)) {
    destination.path <- Project.GetPath(project.name)
    logdebug(paste("Creating project folder", destination.path, "if it does not exists"))
    dir.create(destination.path, showWarnings = FALSE)
    Sys.chmod(destination.path, "777")

    file.ext <- file_ext(FILES$project_file$name)
    filename <- paste(project.name, file.ext, sep=".")
    ##filename <- paste(project.name, "csv", sep=".")
    destination.file <- file.path(destination.path, filename)
    file.copy(FILES$project_file$tmp_name, destination.file, overwrite=TRUE)
    Sys.chmod(destination.file, "777")
    
    if (file.ext == 'zip') {
      unzip(destination.file, exdir = destination.path)
      ## if the csv file exists (was contained in the zip file and then unzipped)
      if (Project.CSVFile.Exist(project.name))
        file.ext = 'csv'
    }
    if (file.ext == 'csv') {
      n.ahead <- ifelse(is.null(POST$nahead), 4, as.numeric(POST$nahead))
      options <- paste("-a", n.ahead)
      msg <- Strategico.ExecCommand(project.name, cmd="import.csv", options=options, mailto=POST$mailto, intern=TRUE)
    }
  }

  if (!is.null(project.name) && !is.null(POST$run) &&  DB.GetTableNameProjectItems(project.name) %in% strategico.tables) {

    options.base <- paste(" --eval.param=\"", POST$param, "\"", sep="")
    options.base <- paste(options.base, "--id.range ")

    ## running parallel jobs
    maxid <- Project.GetMaxID(project.name, db.channel=db.channel)
    if (maxid == 0) {
       msg <- "no items found, cannot run..."
    } else {    
  ##
      id.step <- as.integer(maxid / strategico.config$command.eval.jobs) + 1
      start <- 1
      msg <- ""
      for (c in 1:strategico.config$command.eval.jobs) {
         end <- min(start + id.step, maxid)
         options <- paste(options.base, start, ":", end, sep="")
         msg.new <- Strategico.ExecCommand(project.name, cmd="eval.items", mailto=project.config$mailto, options=options, intern=FALSE)
         msg <- paste(msg, "<br />", msg.new)
         start <- end + 1
      } #end for
    }
  } # end eval.items

  if (!is.null(project.name) && !is.null(POST$export.csv) && DB.GetTableNameProjectItems(project.name) %in% strategico.tables ) {
    msg <- Strategico.ExecCommand(project.name, cmd="export.csv", options="", mailto=project.config$mailto, intern=TRUE)
  }

  if (!is.null(project.name) && !is.null(POST$report.stats) && DB.GetTableNameProjectItems(project.name) %in% strategico.tables ) {
    #msg <- Strategico.ExecCommand(project.name, cmd="report.stats", options="", mailto=project.config$mailto, intern=TRUE)
    Project.BuildStatsHtmlPage(project.name, db.channel=db.channel)
  }

  if (!is.null(project.name) && !is.null(POST$report.suspicious) && DB.GetTableNameProjectItems(project.name) %in% strategico.tables ) {
    #msg <- Strategico.ExecCommand(project.name, cmd="report.suspicious", options="", mailto=project.config$mailto, intern=TRUE)
    for (v in project.values) 
      Project.BuildSuspiciousItemsHtmlPage(project.name, db.channel=db.channel, v)
  }

  if (!is.null(project.name) && !is.null(POST$drop.project)) {
    msg <- Strategico.ExecCommand(project.name, cmd="drop", options="", mailto=project.config$mailto, intern=TRUE)
  }

  if (!is.null(project.name)) {

    exists.csv <- Project.CSVFile.Exist(project.name) 
    exists.config <- Project.ConfigFile.Exist(project.name) 
    ##exists.tables <-DB.GetTableNameProjectItems(project.name) %in% strategico.tables
    project.url.html.link <- sprintf('<a href=%s/%s/  target="_blank">project files</a>', strategico.config$projects.url, project.name)

    b10 <- 'The csv file must have:
          <ul>
           <li>column names KEY1, KEY2, ..., PERIOD, V1, ...</li>
           <li>columns separated by ;</li> 
           <li>decimals with .</li>         
         </ul><br />
       <form enctype="multipart/form-data" method="POST">
       <input name="project.name" type="hidden" value="__PROJECT_NAME__"	 size="10" /> 
       File (csv or config): <input type="file" name="project_file" /><br /> 
       Mail Address: <input name="mailto" type="text" value="" size="20" /><br />
       Predicted points (n.ahead parameter): <input name="nahead" type="text" value="" size="1" /><br />
       <input type="submit" name="import.csv" value="Import"/></form><br />'

    b10 <- gsub("__PROJECT_NAME__", ifelse(is.null(project.name), "", project.name), b10)
    page.sections <- rbind(page.sections, data.frame(title="Import CSV", body=b10))
            
    if (exists.csv && exists.config) { 
    
    b60 <- '<form  method="POST">
       <input name="project.name" type="hidden" value="__PROJECT_NAME__"	 size="10" /> 
   <textarea name="param" rows="6" cols="60">__PARAM__</textarea><br />
                   Press run for starting eval (LTP) job(s) for your project.<br />It can take from few seconds to hours:
                   <input type="submit" name="run" value="Run"/><br /></form>'

	b60 <- gsub("__PROJECT_NAME__", ifelse(is.null(project.name), "", project.name), b60)
        b60 <- gsub("__PARAM__", Param.ToString(project.config$param), b60)
        page.sections <- rbind(page.sections, data.frame(title="Run", body=b60))

        b65 <- sprintf('<form  method="POST">
                <input name="project.name" type="hidden" value="__PROJECT_NAME__"         size="10" />
                <input type="submit" name="report.stats" value="Build Project Stats"/></form><br />')
	b65 <- gsub("__PROJECT_NAME__", ifelse(is.null(project.name), "", project.name), b65)
        b67 <- sprintf('<form  method="POST">
                <input name="project.name" type="hidden" value="__PROJECT_NAME__"         size="10" />
                <input type="submit" name="report.suspicious" value="Build Suspicious Items"/></form><br />See %s', project.url.html.link)
	b67 <- gsub("__PROJECT_NAME__", ifelse(is.null(project.name), "", project.name), b67)
        page.sections <- rbind(page.sections, data.frame(title="Create reports", body=paste(b65, b67, sep="\n")))

        b70 <- '<a href="items.brew?project=__PROJECT_NAME__">browse</a> results'
	b70 <- gsub("__PROJECT_NAME__", ifelse(is.null(project.name), "", project.name), b70)

	page.sections <- rbind(page.sections, data.frame(title="Analysis", body=b70))
        b80 <- paste('Press button to export project results to CSV files: ',
                     '<form  method="POST"><input type="submit" name="export.csv" value="Export"/></form>',
                     '<br />See ', project.url.html.link,
                     sep='')
        page.sections <- rbind(page.sections, data.frame(title="Export CSV", body=b80))

      } ## end exists.config

    b100 <- 'This step will delete this project (database tables and all files). Are you sure??
                <form  method="POST">
                   <input name="project.name" type="hidden" value="__PROJECT_NAME__"	 size="10" /> 
                   <input type="submit" name="drop.project" value="Drop project"/><br />
                </form>'
    b100 <- gsub("__PROJECT_NAME__", ifelse(is.null(project.name), "", project.name), b100)
    page.sections <- rbind(page.sections, data.frame(title=paste("Drop", project.name), body=b100))
  }
  template.file <- file.path(GetWebTemplatesHome(), "page.brew")
  brew(template.file)
%>
